import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';

import api from '@/api';
import req from '@/utils/req';

export const getUser = createAsyncThunk('user/getUser', () =>
  req.get<typeof initialState.info>(api.sys.user.info, {}, { hiddenMsg: true })
);

const initialState = {
  login: false,
  loaded: false,
  info: {
    id: 0,
    account: '',
    name: '',
    email: '',
    isFrozen: false,
    isAdmin: false,
  },
};

const user = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setState(state, action: PayloadAction<Partial<userState>>) {
      Object.assign(state, action.payload);
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getUser.rejected, (state) => {
      state.login = false;
      state.loaded = true;
    });
    builder.addCase(getUser.fulfilled, (state, action) => {
      state.login = true;
      state.info = action.payload;
      state.loaded = true;
    });
  },
});

export type userState = typeof initialState;
export const userReducer = user.reducer;
export const userActions = user.actions;
export default user;
